iT邦幫忙

2025 iThome 鐵人賽

DAY 2
1
Software Development

30 天 Effective C++ 大挑戰!!系列 第 2

[Day 2] Accustoming Yourself to C++

  • 分享至 

  • xImage
  •  

《Effective C++》的第一個章節 —— Accustoming Yourself to C++,其中提到的 4 個知識點已是全書最淺顯易懂的觀念了 QQ

儘管篇幅不長,依舊有許多值得探討的底層邏輯。以下分別介紹:

1. View C++ as a federation of languages

C++ 不應被視為單一程式語言,而是 C、Objected-Oriented C++、Template C++、STL 等程式語言的集合。每種語言之間的特性略有不同:C 的 Array 並不會自動初始化,STL 的 Vector 功能相近卻會自動初始化為 0。

2. Prefer consts, enums, and inlines to #defines

常數請用 constenum 替換掉 define,這個小技巧蠻容易理解的。至於 inline 函式是什麽呢?書中有個簡單的範例,template 則是第 7 章會重點講解的,先按下不表:

template<typename T>
inline void CALL_WITH_MAX(const T& a , const T& b){
    f(a>b?a:b);
}

在此總結使用 #define 的缺點:

  • 編譯器可能看不到後續的常數。 e.g. #define NAME Yoyo 若出現錯誤訊息,僅會提到 Yoyo 而非識別字 NAME,難以 debug
  • 無法使用 private、public、scope 等概念。

3. Use const whenever possible

去年翻閱這本書後,便養成了常數都加上 const 的好習慣。function 亦可宣告為 const。若在同一個 class 中存在 const 版本與 non-const 版本的同名 function,且兩者的實作內容相同,則為了避免無窮迴圈的風險,non-const 版本應該透過「轉型」來呼叫 const 版本的function。

4. Make sure that objects are initialized before they’re used

從大一程設的第一節課開始,教授就不斷提醒我們要記得「初始化」!不只能避免未定義行為造成不可預測的錯誤,更能體現出變數的預計用途從而提高可讀性。

值得注意的是,C++ 的初始化會發生再呼叫建構式之前。換而言之,class 底下的 constructor 並非「初始化」,而是「賦值」。若有初始化 class 的需求,應使用 member initialization list 的方式實作:

ABEntry::ABEntry(const std::string& name, const std::string& address):
    theName(name),
    theAddress(address),
    numTimesConsulted(0)
{}

上一篇
[Day 1] 前言 && 大綱
下一篇
[Day 3] Constructors, Destructors, and Assignment Operators I
系列文
30 天 Effective C++ 大挑戰!!30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言